<?php

namespace apiend\modules\user\models;

use Yii;
use yii\db\Exception;
use common\models\user\User;
use common\models\admin\AdminUser;

/**
 * 个人信息修改模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AdminerForm extends \common\base\Model {

    /**
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @var string 头像
     */
    public $password;

    /**
     * @var User 头像
     */
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            [['password'], 'required'],
            ['password', 'string', 'min' => 8, 'max' => 18],
            ['user_id', 'validateUser'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = User::findOne($this->$attribute);
        if ($user->isAdminer) {
            return $this->addError($attribute, '当前用户已是管理员');
        }
        if (!$user->isStaff) {
            return $this->addError($attribute, '当前要设置成管理人员的用户未入住或未绑定人员信息');
        }
        $this->_user = $user;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'avatar' => '头像',
            'nickname' => '昵称',
            'gender' => '类型',
            'birthday' => '出生日期',
            'location' => '地点',
            'signature' => '个人签名',
        ];
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->_user;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $adminer = new AdminUser();
            $adminer->setAttributes([
                'username' => $user->username,
                'mobile' => $user->decryptMobile(false),
                'realname' => $user->realname,
                'company_id' => $user->company_id,
                'password_hash' => Yii::$app->security->generatePasswordHash($this->password),
                'auth_key' => Yii::$app->security->generateRandomString(),
            ]);
            $adminer->status = AdminUser::STATUS_ACTIVE;
            if (!$adminer->save()) {
                throw new Exception($adminer->getErrorMsg());
            }
            $user->admin_id = $adminer->id;
            if (!$user->save()) {
                throw new Exception($user->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return true;
    }

}
